package com.zhiyou100.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.zhiyou100.model.Repay;
import com.zhiyou100.service.RepayService;
import com.zhiyou100.vo.ResponseVo;

@RestController
public class RepayController {
	@Autowired
	private RepayService repayService;
	@GetMapping("/repays/{projectId}")
	public ResponseVo<ArrayList<Repay>> findAll(@PathVariable int projectId){
		ArrayList<Repay> al = repayService.findAll(projectId);

		return new ResponseVo<ArrayList<Repay>>(200, "请求成功", al);

	}
	@PostMapping("/repays")
	public ResponseVo<String> add(Repay repay,MultipartFile file,HttpServletRequest request){

		String web=request.getServletContext().getRealPath("/");
		String path=web+"/"+file.getOriginalFilename();

		try {
			file.transferTo(new File(path));
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		repay.setIcon1(file.getOriginalFilename());
		repay.setIcon2(file.getOriginalFilename());
		repay.setIcon3(file.getOriginalFilename());

		repayService.add(repay);
		return new ResponseVo<String>(200, "请求成功", null);

	}
	@PostMapping("/repays")
	public ResponseVo<String> update(Repay repay,MultipartFile file,HttpServletRequest request){

		String web=request.getServletContext().getRealPath("/");
		String path=web+"/"+file.getOriginalFilename();

		try {
			file.transferTo(new File(path));
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		repay.setIcon1(file.getOriginalFilename());
		repay.setIcon2(file.getOriginalFilename());
		repay.setIcon3(file.getOriginalFilename());

		repayService.update(repay);
		return new ResponseVo<String>(200, "请求成功", null);
	}
	@DeleteMapping("/repays/{id}")
	public ResponseVo<String> delete(@PathVariable int id){

		repayService.delete(id);

		return new ResponseVo<String>(200, "删除成功", null);
	}
}